using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Linq;

namespace n8d.SyntaxHighlighter.Features.SyntaxHighlighter
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("f694de59-aad7-45b0-896d-55881d05b642")]
    public class SyntaxHighlighterEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        private string[] folderUrls = { "Style Library/SyntaxHighlighter" };

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            if (site != null)
            {
                SPWeb rootWeb = site.RootWeb;

                SPList styleLibrary = rootWeb.Lists.TryGetList("Style Library");
                if (styleLibrary != null)
                {
                    SPListItemCollection folders = styleLibrary.Folders;
                    string featureId = properties.Feature.Definition.Id.ToString();

                    foreach (string folderUrl in folderUrls)
                    {
                        SPFolder folder = GetFolderByUrl(folders, folderUrl);
                        if (folder != null)
                        {
                            PublishFiles(folder);
                        }
                    }
                }
            }

        }

        private static SPFolder GetFolderByUrl(SPListItemCollection folders, string folderUrl)
        {
            if (folders == null)
            {
                throw new ArgumentNullException("folders");
            }

            if (String.IsNullOrEmpty(folderUrl))
            {
                throw new ArgumentNullException("folderUrl");
            }

            SPFolder folder = null;

            SPListItem item = (from SPListItem i
                               in folders
                               where i.Url.Equals(folderUrl, StringComparison.InvariantCultureIgnoreCase)
                               select i).FirstOrDefault();

            if (item != null)
            {
                folder = item.Folder;
            }

            return folder;
        }

        private static void PublishFiles(SPFolder folder)
        {
            if (folder == null)
            {
                throw new ArgumentNullException("folder");
            }

            SPFileCollection files = folder.Files;
            var checkedOutFiles = from SPFile f
                                  in files
                                  where f.Url.IndexOf(folder.Url, StringComparison.OrdinalIgnoreCase) >= 0 &&
                                  f.Level == SPFileLevel.Checkout
                                  select f;


            foreach (SPFile f in checkedOutFiles)
            {
                f.CheckIn(String.Empty, SPCheckinType.MajorCheckIn);
            }
            if (folder.SubFolders.Count > 0)
            {
                foreach (SPFolder subFolder in folder.SubFolders)
                {
                    PublishFiles(subFolder);
                }
            }
        }

        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
